var common = require("../../utils/public.js") //引入public.js脚本
const api = require('../../utils/api.js')
Page({
  data: {
    type: '',
    //数量
    inputNum: '',
    //购物车原有数量
    inputNum1: '',
    cityNumber: '',
    phoneNumber: '',
    cityId: wx.getStorageSync("cityId"),
    num: 0,
    number: 0,
    index: 0,
    gun: true,
    // 未登录时
    login: '',
    navShowed: false,
    nav0Showed: false,
    // 上方横向导航
    nav_list_id: 0,
    type_1: [],
    nav_list: [],
    // 左侧导航
    left_list_id: 0,
    type_2: [],
    loginCode1: false,
    left_list: [],
    // 右侧横向导航
    right_list_id: 0,
    loginCodeL: "",
    type_3: [],
    right_list: [],
    // 底部商品数组
    pro_list: [],
    goodsList: [],
    allId: '',
    rank: 2,
    get_data_finish: false,
    zindex: 0,
    zindex1: 0,
    vipFlag:0
  },
  // 点击导航更换商品大类
  switchTap: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let nav_list_id = e.currentTarget.dataset.id
    let { nav_list } = that.data;
    // 全屏宽度
    let screenWidth = wx.getSystemInfoSync().windowWidth;
    // 每个导航项宽度
    let itemWidth = screenWidth / 5;
    // 计算出当它居中时横向滚动框应该滚动的距离
    let scrollX = itemWidth * index;
    // 所有的导航项的宽度的总和
    let maxScrollX = (nav_list.length + 1) * itemWidth;
    // 这个滚动的距离既不能小于0,也不能比最大的长度还长(这个最大的长度就是所有的导航项的宽度的总和).
    if (scrollX < 0) {
      scrollX = 0;
    } else if (scrollX >= maxScrollX) {
      scrollX = maxScrollX;
    }
    // 然后赋值给x让滚动条滚动.
    that.setData({
      x: scrollX,
      allId: nav_list_id
    })

    // 关闭all菜单
    that.closeNav();
    // 调用type_1_clickHandler
    // nav_list_id ===e.currentTarget.dataset.id
    that.type_1_clickHandler(nav_list_id)
  },
  type_1_clickHandler: function (nav_id) {

    let that = this
    let new_left_list = that.data.type_2.filter(item => { return item.parentId == nav_id })
    let item = {}
    if (nav_id === that.data.nav_list_id) {
      item.id = that.data.left_list_id
    } else {
      item = new_left_list[0]
      // wx.setStorageSync('refreshFenLei', false)
    }
    let id = item ? item.id : ''

    that.setData({
      left_list: new_left_list,
      left_list_id: id,
      nav_list_id: nav_id,
      allId: id
    })
    that.type_2_clickHandler(id)

  },
  switchTap1: function (e) {
    let that = this;
    let scrollY = e.currentTarget.offsetTop;
    let left_list_id = e.currentTarget.dataset.id || e.left_id;
    that.setData({
      y: scrollY,
      left_list_id: left_list_id,
    })
    that.type_2_clickHandler(left_list_id)
  },
  // 二级菜单栏操作
  type_2_clickHandler: function (left_id) {
    let that = this
    let new_right_list = that.data.type_3.filter(item => {
      return item.parentId == left_id
    })
    that.setData({
      right_list: new_right_list,
      right_list_id: "",
      allId: left_id
    })
    // 调用公共接口
    that.classifyShop(left_id, 2);
  },
  switchTap2: function (e) {
    var that = this;
    let scrollX = e.currentTarget.offsetLeft;
    let right_list_id = e.currentTarget.dataset.id;
    that.setData({
      x1: scrollX,
      right_list_id: right_list_id,
      allId: right_list_id,
      rank: 3
    })
    // 关闭菜单0
    that.closeNav0();
    // 调用公共接口
    that.classifyShop(right_list_id, 3)

  },
  // 商品显示接口(公共的)
  classifyShop(rlId, rank) {
    let that = this
    api.getGoods({
      id: rlId,
      rank: rank, //级别
      page: {
        startPage: false, //是否分页
        size: 6 //几条数据
      },
      cityId: wx.getStorageSync('cityId'),
      userId: wx.getStorageSync('openId')
    }).then(res => {
      if(wx.getStorageSync('type') == "2"){
        res.object.records.forEach(v=>{
          v.goodsDetailsEntityList.forEach(j=>{
            api.roleSwitch(j)
          })
        })
      }
      let goods = res.object.records;
      for (var i = 0; i < goods.length; i++) { //遍历数组 给数组元素加上隐藏
        let goodsDetailsEntityList = goods[i].goodsDetailsEntityList
        goods[i].choice = true;
        goodsDetailsEntityList.forEach(v => {
          if (v.amount > 0) {
            goods[i].choice = false;
          }
        })
      }
      that.setData({
        goodsList: goods
      })
    })
  },
  // 跳转到详情
  next: common.throttleFunc(function (e) {
    let { shopid, id } = e.currentTarget.dataset;
    if (wx.getStorageSync("type") == -1) {
      wx.showToast({
        title: '请您先进行身份选择',
        icon: 'none',
        duration: 1500
      })
      wx.navigateTo({
        url: '/pages/sf_xz/sf_xz?type=' + 1,
      })
    } else if (wx.getStorageSync("type") == 1 ) {
      if (wx.getStorageSync('codeNum') == 103) {
        //未注册商铺 跳转商铺注册页
        wx.showToast({
          title: '您还未注册店铺！',
          icon: 'none',
          duration: 1500
        })

        wx.navigateTo({
          url: '/pages/type/type',
        })

      } else if (wx.getStorageSync('codeNum') == 104) {
        //商铺审核中 
        wx.showToast({
          title: '您的商铺审核中！',
          icon: 'none',
          duration: 1000
        })

        wx.navigateTo({
          url: '/pages/shopBack/shopBack?type=' + 1,
        })

      } else if (wx.getStorageSync('codeNum') == 105) {
        //商铺审核未通过
        wx.showToast({
          title: '您申请的店铺暂未审核通过！',
          icon: 'none',
          duration: 1000
        })

        wx.navigateTo({
          url: '/pages/type/type',
        })

      } else if (wx.getStorageSync('codeNum') == 99) {

        //登录跳转商品详情界面
        wx.navigateTo({
          url: '/pages/detail/detail?id=' + id + '&shopid=' + shopid,
        })
      }
    } else if (wx.getStorageSync("type") == 2) {
      if (wx.getStorageSync('codeNum') != 99) {
        wx.showToast({
          title: '请您先注册一个收货地址',
          icon: 'none',
          duration: 1500
        })
        wx.navigateTo({
          url: '/pages/edit-address/edit-address',
        })
      } else {
        //登录跳转商品详情界面
        wx.navigateTo({
          url: '/pages/detail/detail?id=' + id + '&shopid=' + shopid,
        })
      }
    } else if (wx.getStorageSync('codeNum') == 99) {

      //登录跳转商品详情界面
      wx.navigateTo({
        url: '/pages/detail/detail?id=' + id + '&shopid=' + shopid,
      })
    }else {
      wx.navigateTo({
        url: '/pages/userMess/userMess',
      })
    }

  }),
  onLoad: function () {
    this.setData({
      type: wx.getStorageSync('type')
    })
    let that = this;
    let query = wx.createSelectorQuery();
    query.select('.index_tab1').boundingClientRect(function (rect) {
      that.setData({
        height: 54 + 'px'
      })
    }).exec();
    // 打电话（城市电话  客户经理电话）
    api.phoneList({
      id: wx.getStorageSync("cityId")
    }).then(res => {
      if (res.result) {
        that.setData({
          cityNumber: res.body.cityInfo,
          phoneNumber: res.body.customerManager,
        })
      }
    })
    // 获取分类列表
    api.getType({
      "cityId": wx.getStorageSync("cityId")
    }).then(res => {
      let data = res.body;
      let nav_list = data.goodsType1
      let type_2 = data.goodsType2
      let type_3 = data.goodsType3
      this.setData({
        nav_list,
        type_2,
        type_3,
        get_data_finish: true
      })
      let that = this;
      let { allId, rank } = that.data;
      if (that.data.get_data_finish) {
        let navId = wx.getStorageSync("navId") ? wx.getStorageSync("navId") : (nav_list[0] ? nav_list[0].id : '')
        let screenWidth = wx.getSystemInfoSync().windowWidth;
        let zindex = 0
        zindex = nav_list.findIndex((v, i) => v.id == navId)
        let itemWidth = screenWidth / 5;
        let scrollX = itemWidth * zindex;
        that.setData({
          x: scrollX
        })

        that.type_1_clickHandler(navId)
        wx.removeStorage({
          key: 'navId',
        })
      } else {
        // 显示右侧商品
        that.classifyShop(allId, rank);
        if(that.data.login){
          that.getShopSum()
        }
        let nav_id = nav_list[0].id
        let left_list = this.type_1_clickHandler(nav_id)
        let left_id = left_list[0].id
      }
    })
  },
  onShow: function () {
    let that = this;
    that.setData({
      login: wx.getStorageSync('token') ? wx.getStorageSync('codeNum') == 99 ? true : false : false,
      loginCode: wx.getStorageSync('codeNum') == 103 ? true : wx.getStorageSync('codeNum') == 105 ? true : false,
      loginCode1: wx.getStorageSync('codeNum') == 104 ? true : false,
      vipFlag: Number(wx.getStorageSync('vipFlag')) 
    })
    let { allId, rank } = that.data;
    if (that.data.get_data_finish && wx.getStorageSync("navId")) {
      let navId = wx.getStorageSync("navId")
      let screenWidth = wx.getSystemInfoSync().windowWidth;
      let nav_list = that.data.nav_list
      let zindex = 0
      zindex = nav_list.findIndex((v, i) => v.id == navId)
      let itemWidth = screenWidth / 5;
      let scrollX = itemWidth * zindex;
      if (!!navId) {
        that.type_1_clickHandler(navId)
      } else {
        that.type_1_clickHandler(that.data.nav_list_id)
      }
      that.setData({
        x: scrollX
      })
      wx.removeStorage({
        key: 'navId',
      })
    } else {
      // 显示右侧商品
      that.classifyShop(allId, rank);
      if(that.data.login){
        that.getShopSum()
      }
    }
  },
  // 购物车数量
  getShopSum() {
    let that = this;
    api.get_cart({
      cityId: wx.getStorageSync("cityId"),
      userId: wx.getStorageSync("openId"),
      page: {}
    }).then(res => {
      let getSum = res.data.body.getSum;
      if (getSum > 0) {
        wx.setTabBarBadge({
          index: 3,
          text: getSum + '' //显示的内容 
        })
      }
    })
  },
  //增加数量
  addCount: function (e) {
    let that = this
    let { index1, index } = e.currentTarget.dataset;
    let goodsList = that.data.goodsList;
    let goLists = goodsList[index].goodsDetailsEntityList[index1];
    let startNum = goodsList[index].goodsDetailsEntityList[index1].startNum
    let amount = goLists.amount;
    if (amount < startNum) {
      amount = startNum;
    } else {
      amount = Number(amount) + 1
    }
    that.nums(amount, index, goodsList, goLists);
  },
  //减少数量(+ -)
  btnMinus(e) {
    let that = this
    let { index1, index } = e.currentTarget.dataset;
    let goodsList = that.data.goodsList;
    let goLists = goodsList[index].goodsDetailsEntityList[index1];
    let startNum = goodsList[index].goodsDetailsEntityList[index1].startNum
    let amount = goLists.amount;
    if (amount == startNum) {
      amount = 0;
    } else {
      amount = amount - 1;
    }

    that.nums(amount, index, goodsList, goLists);

  },
  //调用商品接口(公共接口)
  nums(number, index, goodsList, goLists) {
    let that = this
    let amount = number;
    let userInfoId = wx.getStorageSync('openId');
    let cityId = wx.getStorageSync('cityId')
    let goodsName = goodsList[index].name;
    let goodsDetailsId = goLists.id;
    let price = goLists.price;
    let totalPrice = goLists.priceVip;
    // 价格
    if (goLists.activitySeckillId == null) {
      if (wx.getStorageSync("vipFlag") == 1) {
        price =goLists.salesPriceVip
        totalPrice = price * amount
      } else {
        price =goLists.salesPrice
        totalPrice = price * amount
      }
    } else {
      price = goLists.seckillPrice
      totalPrice = price * amount
    }
    api.set_amount({
      cityId,
      userInfoId,
      goodsName,
      goodsDetailsId,
      amount,
      price,
      totalPrice
    }).then(res => {
      if (res.result) {
        goLists.amount = amount;
        if (res.data > 0) {
          wx.setTabBarBadge({
            index: 3,
            text: res.data //显示的内容 
          })
        } else {
          wx.hideTabBarRedDot({
            index: 3
          })
        }
        that.setData({
          goodsList: goodsList
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })

  },
  // 首页打电话
  callGetPhone: function () {
    wx.navigateTo({
      url: '/pages/kefu/kefu',
    })
  },
  // 打开菜单0
  openNav0: function () {
    this.setData({
      nav0Showed: true,
      gun: false
    });
  },
  // 打开菜单
  openNav: function () {
    this.setData({
      navShowed: true,
      nav0Showed: false,
      gun: true
    });
  },
  // 关闭菜单
  closeNav: function () {
    this.setData({
      navShowed: false,
      nav0Showed: false,
      gun: true
    });
  },
  // 关闭菜单0
  closeNav0: function () {
    this.setData({
      nav0Showed: false,
      gun: true
    });
  },
  //选规格
  more(e) {
    let that = this
    // 获取选中的index索引
    var index = e.currentTarget.dataset.index;
    // 获取到商品列表数据
    var goodsList = that.data.goodsList;
    // 循环数组数据，判断----规格 --收起
    goodsList[index].choice = !goodsList[index].choice;
    //重新渲染数据
    that.setData({
      goodsList: goodsList
    })

  },
  // 顶部搜索
  handleSearch() {
    wx.navigateTo({
      url: '/pages/search_index/search_index',
    })
  },
  onShareAppMessage() { 
    return {
      title: '京天鲜生, 生鲜管家',
      path: '/pages/index/index',
      imageUrl: '../../images/share.jpeg', // 可以更换分享的图片
    }
  },
  //获取数量
  inputNum(e) {
    let that = this
    if (e.detail.value == "" || e.detail.value == 0) {
      that.setData({
        inputNum: that.data.inputNum1
      })
    } else {
      let vals = Number(e.detail.value)
      that.setData({
        inputNum: vals
      })
    }
  },

  //获取焦点
  bindconfocus(e) {
    let index = e.currentTarget.dataset.index
    let index1 = e.currentTarget.dataset.index1
    this.setData({
      zindex: index,
      zindex1: index1,
      inputNum1: e.currentTarget.dataset.item.goodsDetailsEntityList[index1].amount,
      goodsName: e.currentTarget.dataset.item.name,
      goodsDetailsId: e.currentTarget.dataset.item.goodsDetailsEntityList[index1].id,
      price: e.currentTarget.dataset.item.goodsDetailsEntityList[index1].price,
      totalPrice: e.currentTarget.dataset.item.goodsDetailsEntityList[index1].priceVip,
      //起送数量
      detailStartNum: e.currentTarget.dataset.item.goodsDetailsEntityList[index1].startNum,
    })
  },
  //失去焦点
  bindconfirm(e) {
    var that = this;
    if (that.data.inputNum >= that.data.detailStartNum) {
      if (that.data.inputNum == "") {

      } else {
        let { zindex, zindex1 } = that.data;
        let userInfoId = wx.getStorageSync("openId")
        let cityId = wx.getStorageSync("cityId")
        let goodsName = that.data.goodsName
        let goodsDetailsId = that.data.goodsDetailsId
        let price = that.data.price
        let amount = Number(that.data.inputNum)
        let totalPrice = that.data.totalPrice
        let goodsList = that.data.goodsList
        // // carts[that.data.indexs].amount = that.data.inputNum;
        // // that.setData({
        // //   carts: carts
        // // });

        api.set_amount({
          cityId,
          userInfoId,
          goodsName,
          goodsDetailsId,
          amount,
          price,
          totalPrice
        }).then(res => {
          if (res.result) {
            goodsList[zindex].goodsDetailsEntityList[zindex1].amount = that.data.inputNum;
            that.setData({
              goodsList
            });
            if (res.data > 0) {
              wx.setTabBarBadge({
                index: 3,
                text: res.data //显示的内容 
              })
            } else {
              wx.hideTabBarRedDot({
                index: 3
              })
            }
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none'
            })
            goodsList[zindex].goodsDetailsEntityList[zindex1].amount;
            that.setData({
              goodsList
            });
          }

        })
      }
    } else {

      if (that.data.inputNum != "") {
        wx.showToast({
          title: '请输入最小起送数量' + that.data.detailStartNum,
          icon: 'none'
        })
      }

    }
  }
})